<?php


namespace app\admin\controller\v1;


use app\admin\model\AdModel;
use app\admin\Validate\ad\AddAdValidate;
use app\admin\Validate\ad\GetAdListValidate;
use app\admin\Validate\ad\UpdateAdValidate;
use app\admin\Validate\ad\UpdateAdStatusByIdValidate;
use app\BaseController;
use app\common\Token;
use app\common\validate\IdMustIntValidate;

class Ad extends BaseController
{
    /**
     * 添加广告
     * @return \think\response\Json
     */
    public function addAd() {
        Token::checkToken($this->request);
        $param = (new AddAdValidate())->validateParam();
        $param['add_time'] = getDateTime();
        $model = new AdModel();
        $result = $model->save($param);
        if($result){
            return successJson(true, "添加成功");
        }
        return errorJson(60001, "添加失败");
    }

    /**
     * 根据id删除
     * @param int $id
     * @return \think\response\Json
     */
    public function deleteAdById(int $id) {
        Token::checkToken($this->request);
        (new IdMustIntValidate())->validateParam();
        $bool = AdModel::destroy($id);
        if($bool){
            return successJson(true, "删除成功");
        }
        return errorJson(60002, "删除失败");
    }

    /**
     * 更新广告数据
     * @return \think\response\Json
     */
    public function updateAd() {
        Token::checkToken($this->request);
        $param = (new UpdateAdValidate())->validateParam();
        $bool = AdModel::update($param);
        if($bool){
            return successJson(true, "添加成功");
        }
        return errorJson(60003, "删除失败");
    }

    /**
     * 查询失败
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function getAdList() {
        Token::checkToken($this->request);
        $param = (new GetAdListValidate())->validateParam();
        $model = new AdModel();
        $result = $model->toPaginate($param);
        if($result){
            return successJson($result, "查询成功");
        }
        return errorJson(60004, "查询失败");
    }

    /**
     * 更新状态
     * @return \think\response\Json
     */
    public function updateAdStatusBydId() {
        Token::checkToken($this->request);
        $param = (new UpdateAdStatusByIdValidate())->validateParam();
        $bool = AdModel::update($param);
        if($bool){
            return successJson(true, "更新成功");
        }
        return errorJson(60003, "更新失败");
    }

    /**
     * 根据ID获取数据
     * @param int $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAdById(int $id) {
        Token::checkToken($this->request);
        (new IdMustIntValidate())->validateParam();
        $result = AdModel::find($id);
        if($result){
            return successJson($result, "查询成功");
        }
        return errorJson(60004, "查询失败");
    }
}